import { Form, Input, Select } from "antd";
import { useComponentsStore } from "@/stores/edit-pages-store";
import { useEffect, useState } from "react";
import { omit } from "lodash-es";
import { ApiConf, ApiMethod, InterfaceConfSelector } from "@/pages/lowCodeEditorPlus/components/Setting/selectors/InterfaceConfSelector";

export interface SendRequestConfig {
  type: "sendRequest";
  label: string;
  config: {
    api: ApiConf
    outputVar: string; //default: responseResult
    options: {
      silent?: boolean;
    };
    ignoreError: boolean; //default: false
  };
}
// dataType
// json: 发送体格式为：application/json，当发送内容中存在文件时会自动使用 form-data 格式。
// form-data: 发送体格式为：multipart/form-data，当发送内容中存在文件时会自动使用 form-data 格式。
// form: 发送体格式为：application/x-www-form-urlencoded，当发送内容中存在文件时会自动使用 form-data 格式
interface SendRequestProps {
  value?: SendRequestConfig["config"];
  defaultValue?: SendRequestConfig["config"];
  onChange?: (config: SendRequestConfig) => void;
}
export const sendRequestMsg = {
  type: "sendRequest",
  label: "发送请求",
  desc: "配置并发送API请求",
};
const initValue = {
  api: {
    url: "",
    method: "get" as ApiMethod,
  },
  outputVar: "responseResult",
  options: {},
  ignoreError: false,
}
export function SendRequest(props: SendRequestProps) {
  let { value: val, defaultValue, onChange } = props;
  const [form] = Form.useForm();

  const [config, setConfig] = useState<SendRequestConfig["config"]>(initValue);
  useEffect(() => {
    if (val) {
      form.setFieldsValue(val);
      setConfig({...config,...val})
    }else{
      form.setFieldsValue(initValue);
    }
  }, [val]);
  
  function propsChange(changeValues: Partial<SendRequestConfig["config"]>) {
    setConfig({...config,...changeValues})
    onChange?.({
      ...omit(sendRequestMsg,'desc') as Omit<SendRequestConfig, "config">,
      config: {...config,...changeValues}
    });
  }
  return (
    <div className="px-4">
      <Form
        form={form}
        onValuesChange={propsChange}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 13 }}
        labelAlign="right"
        labelWrap
        colon={false}
        className="smallText"
      >
        <Form.Item label="配置请求" name="api">
          <InterfaceConfSelector/>
        </Form.Item>
      </Form>
    </div>
  );
}
